//
//  BSZBaseRequest.m
//  BuSuanZi
//
//  Created by staff on 3/15/25.
//

#import "BSZBaseRequest.h"
#import "BSZHTTPSessionManager.h"
#import "NWJSONParser.h"

@implementation BSZBaseRequest

/**
 POST 请求数据
 
 @param URLString 服务器地址
 @param parameters 字典 token
 @param modelClass 需要的Model类型（自己创建，但必须继承于YWHModel，如果为空则直接返回原始数据）
 @param result 返回结果
 */
+ (void)POST:(nonnull NSString *)URLString
  parameters:(nullable NSDictionary *)parameters
  modelClass:(nullable Class)modelClass
      result:(BSZBaseRequestResult _Nullable )result{
    BSZHTTPSessionManager *manager = [BSZHTTPSessionManager sharedClient];
    [manager POST:[NSString stringWithFormat:@"%@%@",ServerAdress,URLString] parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        BSZLLog(@"url---:%@ \nparamters---:%@ \nresult---:%@",[NSString stringWithFormat:@"%@%@",ServerAdress,URLString],parameters,responseObject);
        NSString *status = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        NSString *msg = [NSString stringWithFormat:@"%@",responseObject[@"msg"]];
        
        if (modelClass) {
            if (status.intValue == 1) {
                //  有效数据Data
                id object = [NWJSONParser parserjson:responseObject[@"result"]];
                
                // 如果为字符串则直接转成字典格式
                if ([object isKindOfClass:[NSString class]]) object = @{@"content":object};
                
                // 如果Obj有数据
                result([self modelClass:modelClass obj:object], status, msg);
                
            }else{
                result(nil,status,msg);
            }
        }else {
            result([NWJSONParser parserjson:responseObject],status,msg);
//            if (responseObject != nil) {
//                result([NWJSONParser parserjson:responseObject],status,msg);
//            }else{
//                result([NWJSONParser parserjson:responseObject],@"-1",@"暂无数据");
//            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        result(nil,[NSString stringWithFormat:@"%ld",(long)error.code],@"服务器错误^_^");
        BSZLLog(@"url---:%@ \nparamters---:%@ \n",[NSString stringWithFormat:@"%@%@",ServerAdress,URLString],parameters);
    }];
}

/**
 GET 请求数据
 
 @param URLString 服务器地址
 @param parameters 字典 token
 @param modelClass 需要的Model类型（自己创建，但必须继承于YWHModel，如果为空则直接返回原始数据）
 @param result 返回结果
 */
+ (void)GET:(nonnull NSString *)URLString
  parameters:(nullable NSDictionary *)parameters
  modelClass:(nullable Class)modelClass
      result:(BSZBaseRequestResult _Nullable )result{
    BSZHTTPSessionManager *manager = [BSZHTTPSessionManager sharedClient];
    //添加请求头
    [manager.requestSerializer setValue:(Token == nil ? @"" : Token) forHTTPHeaderField:@"XX-Token"];
    [manager GET:[NSString stringWithFormat:@"%@%@",ServerAdress,URLString] parameters:parameters headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        BSZLLog(@"url---:%@ \nparamters---:%@ \nresult---:%@",[NSString stringWithFormat:@"%@%@",ServerAdress,URLString],parameters,responseObject);
        NSString *status = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        NSString *msg = [NSString stringWithFormat:@"%@",responseObject[@"msg"]];
        
        if (![NSStringFromClass(modelClass) isEqualToString:@"MallPageConfirmPayDataModel"]) {//非支付类型
            if (modelClass) {
                if (status.intValue == 1) {
                    id object = [[modelClass alloc]initWithDictionary:responseObject error:nil];
                    result(object, status, msg);
                }else{
                    result(nil,status,msg);
                }
            }else {
                result([NWJSONParser parserjson:responseObject],status,msg);
            }
        }else{//支付类型
            if (status.intValue == 200) {
                id object = [[modelClass alloc]initWithDictionary:responseObject error:nil];
                result(object, status, msg);
            }else{
                result(nil,status,msg);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        result(nil,[NSString stringWithFormat:@"%ld",(long)error.code],@"服务器错误^_^");
        BSZLLog(@"url---:%@ \nparamters---:%@ \n",[NSString stringWithFormat:@"%@%@",ServerAdress,URLString],parameters);
    }];
}

/**
 * 上传单个视频/图片
 * parameters: 包含类型/小区Id
 * type=0上传图片 type=1上传视频
 */
+ (void)upFile:(nonnull  NSData*)data
          type:(nonnull NSString *)type
           url:(nonnull NSString *)URLString
            parameters:(nullable NSDictionary *)parameters
            modelClass:(nullable Class)modelClass
      result:(BSZBaseRequestResult _Nullable )result{
    BSZHTTPSessionManager *manager = [BSZHTTPSessionManager sharedClient];
    //添加请求头
    [manager.requestSerializer setValue:(Token == nil ? @"" : Token) forHTTPHeaderField:@"XX-Token"];
    [manager POST:[NSString stringWithFormat:@"%@%@",ServerAdress,URLString] parameters:parameters headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        // 可以在上传时使用当前的系统事件作为文件名
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        if ([type integerValue] == 1) {//视频
            NSString *fileName = [NSString stringWithFormat:@"%@.mp4", str];

            [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"video/mp4"];
        }else if ([type integerValue] == 2) {//音频
            NSString *fileName = [NSString stringWithFormat:@"%@.mp3", str];

            [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"audio/mp3"];
        }else{//图片
            NSString *fileName = [NSString stringWithFormat:@"%@.png", str];

            [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/jpeg"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        BSZLLog(@"数据---：%@",responseObject);
        NSString *status = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        NSString *msg = [NSString stringWithFormat:@"%@",responseObject[@"msg"]];
        
        if (modelClass) {
            if (status.intValue == 1) {
                id object = [[modelClass alloc]initWithDictionary:responseObject error:nil];
                result(object, status, msg);
            }else{
                result(nil,status,msg);
            }
        }else {
            result([NWJSONParser parserjson:responseObject],status,msg);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        result(nil,[NSString stringWithFormat:@"%ld",(long)error.code],@"服务器错误^_^");
    }];
}


+ (id)modelClass:(Class)modelClass obj:(id)obj {
    if ([obj isKindOfClass:[NSArray class]]) {
        return [self modelArrayWithClass:modelClass json:obj];
//        return [NSArray modelArrayWithClass:modelClass json:obj];
    }else if ([obj isKindOfClass:[NSDictionary class]]) {
        return [self modelDictionaryWithClass:modelClass json:obj];
//        return [NSDictionary modelDictionaryWithClass:modelClass json:obj];
    }else {
        return nil;
    }
}

#pragma mark -- 数组转Model
+ (NSArray *)modelArrayWithClass:(Class)cls json:(id)json {
    if (!json) return nil;
    NSArray *arr = nil;
    NSData *jsonData = nil;
    if ([json isKindOfClass:[NSArray class]]) {
        arr = json;
    } else if ([json isKindOfClass:[NSString class]]) {
        jsonData = [(NSString *)json dataUsingEncoding : NSUTF8StringEncoding];
    } else if ([json isKindOfClass:[NSData class]]) {
        jsonData = json;
    }
    if (jsonData) {
        arr = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:NULL];
        if (![arr isKindOfClass:[NSArray class]]) arr = nil;
    }
    return [self modelArrayWithClass:cls array:arr];
}
+ (NSArray *)modelArrayWithClass:(Class)cls array:(NSArray *)arr {
    if (!cls || !arr) return nil;
    NSMutableArray *result = [NSMutableArray new];
    for (NSDictionary *dic in arr) {
        if (![dic isKindOfClass:[NSDictionary class]]) continue;
        NSObject *obj= [cls modelObjectWithDictionary:dic];
        if (obj) [result addObject:obj];
    }
    return result;
}

#pragma mark --字典转Model
+ (NSDictionary *)modelDictionaryWithClass:(Class)cls json:(id)json {
    if (!json) return nil;
    NSDictionary *dic = nil;
    NSData *jsonData = nil;
    if ([json isKindOfClass:[NSDictionary class]]) {
        dic = json;
    } else if ([json isKindOfClass:[NSString class]]) {
        jsonData = [(NSString *)json dataUsingEncoding : NSUTF8StringEncoding];
    } else if ([json isKindOfClass:[NSData class]]) {
        jsonData = json;
    }
    if (jsonData) {
        dic = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:NULL];
        if (![dic isKindOfClass:[NSDictionary class]]) dic = nil;
    }
    return [self modelDictionaryWithClass:cls dictionary:dic];
}
+ (NSDictionary *)modelDictionaryWithClass:(Class)cls dictionary:(NSDictionary *)dic {
    if (!cls || !dic) return nil;
    NSMutableDictionary *result = [NSMutableDictionary new];
    for (NSString *key in dic.allKeys) {
        if (![key isKindOfClass:[NSString class]]) continue;
        NSObject *obj= [cls modelObjectWithDictionary:dic[key]];
        if (obj) result[key] = obj;
    }
    return result;
}

+ (instancetype)modelObjectWithDictionary:(NSDictionary *)dict {
    return [[self alloc] initWithDictionary:dict];
}

- (instancetype)initWithDictionary:(NSDictionary *)infoDic{
    self = [super init];
    if (self) {
        [infoDic enumerateKeysAndObjectsUsingBlock:
                 ^(id key, id obj, BOOL *stop)
                 {
                     id value = obj;
                     if ([obj isKindOfClass:[NSNumber class]])
                     {
                     if (strcmp([obj objCType], @encode(BOOL)) != 0)
                     {
                             @try
                             {
                                 value = [NSString stringWithFormat:@"%@",[obj stringValue]];
                             }
                             @catch (NSException * e)
                             {
                                 if ([[e name] isEqualToString:NSInvalidArgumentException])
                               {
                                     NSNumber *temp =[NSNumber numberWithBool:[obj boolValue]];
                                     value =  [NSString stringWithFormat:@"%@",[temp stringValue]];
                                }
                             }
                         }
                     }
                     else if([obj isKindOfClass:[NSNull class]])
                     {
                         value = @"";
                     }
                     [self setValue:value forKey:key];
                   }];
    }
    return self;
}

@end
